package com.jingdianjichi.subject.infra.config;

import com.jingdianjichi.subject.common.util.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;





/**
 *填充createBy,createTime等公共字段的拦截器
 */
@Component
@Slf4j
/**
 * MappedStatement 映射的 SQL 语句
 * Object 传递给 SQL 语句的参数
 */
@Intercepts({@Signature(type = Executor.class ,method = "update",args = {
        MappedStatement.class, Object.class
})})
public class MybatisInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //mappedStatement在invocation.getArgs()[0]的位置
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        //sql类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        //方法的参数实体
        Object parameter = invocation.getArgs()[1];
        if (parameter == null){
            return invocation.proceed();
        }
        //获取当前登录用户的id
        String loginId = LoginUtil.getLoginId();
        if (StringUtils.isBlank(loginId)){
            return invocation.proceed();
        }
        if (SqlCommandType.INSERT == sqlCommandType || SqlCommandType.UPDATE == sqlCommandType){
            replaceEntityProperty(parameter,loginId,sqlCommandType);
        }

        return invocation.proceed();
    }

    private void replaceEntityProperty(Object parameter, String loginId, SqlCommandType sqlCommandType) {
        if (parameter instanceof Map){
            replaceMap((Map) parameter,loginId,sqlCommandType);
        }else {
            replace(parameter, loginId ,sqlCommandType);
        }

    }

    private void replace(Object parameter ,String loginId ,SqlCommandType sqlCommandType){
        if (SqlCommandType.INSERT == sqlCommandType){
            dealInsert(parameter,loginId);
        }else {
            dealUpdate(parameter,loginId);
        }
    }

    private void replaceMap(Map parameter ,String loginId, SqlCommandType sqlCommandType){
        //parameter.values()返回Map的值
        for (Object val : parameter.values()) {
            replace(val, loginId ,sqlCommandType);
        }
    }

    private void dealInsert(Object parameter, String loginId) {
        Field[] fields = getAllFields(parameter);
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                //获取字段在 parameter 对象中的实际值
                Object o = field.get(parameter);
                if (Objects.nonNull(o)){
                    field.setAccessible(false);
                    continue;
                }
                if ("isDeleted".equals(field.getName())){
                    field.set(parameter,0);
                    field.setAccessible(false);
                } else if ("createdBy".equals(field.getName())){
                    field.set(parameter,loginId);
                    field.setAccessible(false);
                } else if ("createdTime".equals(field.getName())){
                    field.set(parameter,new Date());
                    field.setAccessible(false);
                } else {
                    field.setAccessible(false);
                }

            } catch (IllegalAccessException e) {
                log.error("dealInsert.error:{}",e.getMessage(),e);
            }
        }
    }


    private void dealUpdate(Object parameter, String loginId) {
        Field[] fields = getAllFields(parameter);
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                //获取字段在 parameter 对象中的实际值
                Object o = field.get(parameter);
                if (Objects.nonNull(o)){
                    field.setAccessible(false);
                    continue;
                }
                if ("updateBy".equals(field.getName())){
                    field.set(parameter,loginId);
                    field.setAccessible(false);
                } else if ("updateTime".equals(field.getName())){
                    field.set(parameter,new Date());
                    field.setAccessible(false);
                } else {
                    field.setAccessible(false);
                }

            } catch (IllegalAccessException e) {
                log.error("dealUpdate.error:{}",e.getMessage(),e);
            }
        }
    }





    private Field[] getAllFields(Object object){
        //获取对象的运行时类
        Class<?> clazz = object.getClass();
        //初始化字段列表
        List<Field> fieldList = new ArrayList<>();
        //遍历类及其父类
        while (clazz != null){
            //获取当前类中声明的所有字段clazz.getDeclaredFields()
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            //获取当前类的父类 如果当前类没有父类（即 clazz == null），循环结束
            clazz = clazz.getSuperclass();
        }
        //将字段列表转换为数组
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
